package com.dream.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.dream.commons.result.PageInfo;
import com.dream.commons.result.Tree;
import com.dream.commons.scan.MyException;
import com.dream.commons.utils.BeanUtils;
import com.dream.commons.utils.StringUtils;
import com.dream.mapper.RoleMapper;
import com.dream.mapper.RoleResourceMapper;
import com.dream.mapper.UserRoleMapper;
import com.dream.model.Resource;
import com.dream.model.Role;
import com.dream.model.RoleResource;
import com.dream.model.User;
import com.dream.model.DTO.roleDto.RoleDto;
import com.dream.model.DTO.roleDto.RoleListReqDto;
import com.dream.service.RoleService;
/**
 *
 * Role 表数据服务层接口实现类
 *
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private RoleResourceMapper roleResourceMapper;
    
    @Override
    public List<Role> selectAll() {
        EntityWrapper<Role> wrapper = new EntityWrapper<Role>();
        wrapper.orderBy("seq");
        return roleMapper.selectList(wrapper);
    }

    @Override
    public Object selectTree() {
        List<Tree> trees = new ArrayList<Tree>();
        List<Role> roles = this.selectAll();
        for (Role role : roles) {
            Tree tree = new Tree();
            tree.setId(role.getId());
            tree.setText(role.getName());

            trees.add(tree);
        }
        return trees;
    }

    /**
     * 更新数据
     */
    @Override
    public void updateRole(RoleDto roleDto) {
        // 先删除后添加,有点爆力
        RoleResource roleResource = new RoleResource();
        roleResource.setRoleId(roleDto.getId());
        roleResourceMapper.delete(new EntityWrapper<RoleResource>(roleResource));   
        for (String resourceId : roleDto.getMenus()) {
            roleResource = new RoleResource();
            roleResource.setRoleId(roleDto.getId());
            roleResource.setResourceId(Long.parseLong(resourceId));
            roleResourceMapper.insert(roleResource);
        }     
        Role role = new Role();
    	BeanUtils.copy(roleDto, role); 
    	roleMapper.updateById(role);
    }

    @Override
    public List<Long> selectResourceIdListByRoleId(Long id) {
        return roleMapper.selectResourceIdListByRoleId(id);
    }
    
    @Override
    public Map<String, Set<String>> selectResourceMapByUserId(Long userId) {
        Map<String, Set<String>> resourceMap = new HashMap<String, Set<String>>();
        List<Long> roleIdList = userRoleMapper.selectRoleIdListByUserId(userId);
        Set<String> urlSet = new HashSet<String>();
        Set<String> roles = new HashSet<String>();
        for (Long roleId : roleIdList) {
            List<Map<Long, String>> resourceList = roleMapper.selectResourceListByRoleId(roleId);
            if (resourceList != null) {
                for (Map<Long, String> map : resourceList) {
                    if (StringUtils.isNotBlank(map.get("url"))) {
                        urlSet.add(map.get("url"));
                    }
                }
            }
            Role role = roleMapper.selectById(roleId);
            if (role != null) {
                roles.add(role.getName());
            }
        }
        resourceMap.put("urls", urlSet);
        resourceMap.put("roles", roles);
        return resourceMap;
    }

     /**
      * 新增角色
      */
	@Override
	public void insertByDto(RoleDto roleDto) {
		Role role = BeanUtils.copy(roleDto, Role.class);
        this.insert(role);
		String[] recIds = roleDto.getMenus();
		for (String recId : recIds) {
			RoleResource roleResource = new RoleResource();
			roleResource.setRoleId(role.getId());
			roleResource.setResourceId(Long.parseLong(recId));
			roleResourceMapper.insert(roleResource);
		}   
	}
     
	/**
	 * 角色数据列表
	 */
	@Override
	public PageInfo<Role> selectDataGrid(RoleListReqDto roleListReqDto) {
		Page<Role> page = new Page<Role>();
		page.setCurrent(roleListReqDto.getPage());
		page.setSize(roleListReqDto.getLimit());
		String roleName = roleListReqDto.getRoleName();
		EntityWrapper<Role> ew = new EntityWrapper<Role>();
		if (StringUtils.isNotBlank(roleName)) {
			ew.like("name", roleName);
		}
		ew.orderBy("seq", true);
		Page<Role> pageInfo = this.selectPage(page, ew);
		PageInfo<Role> into = new PageInfo<Role>(pageInfo.getTotal(), pageInfo.getRecords());
		return into;
	}
    
	/**
	 * 根据id删除角色
	 */
	@Override
	public void deleteRoleById(Long id) {
		 this.deleteById(id);
		 roleResourceMapper.deleteByRoleId(id);
	}
    
	/**
	 * 批量删除角色
	 */
	@Override
	public int deleteRoles(String[] ids) {
		List<String> idsList = Arrays.asList(ids);
		for (String id : idsList) {
			roleResourceMapper.deleteByRoleId(Long.parseLong(id));
		}
		int s = roleMapper.deleteBatchIds(idsList);
		if (s <= 0) {
			String msg ="操作失败";
			throw new MyException(msg);
		}
		return s;
	}
  
	/**
	 * 根据id查询role
	 */
	@Override
	public Role selectById(String id) {
	    EntityWrapper<Role> wrapper = new EntityWrapper<Role>();
        wrapper.eq("id", id);
        List<Role> roleList = roleMapper.selectList(wrapper);
        Role role = roleList.get(0);
        return role;
	}



}